<?php
namespace App\Admin\Controllers\File;

use App\Models\Basics\AmazonCountry;
use App\Models\Basics\AmazonArea;
use App\Models\File\FileStore;
use App\Admin\Actions\File\Store\ImportFile;
use App\Util\User;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
class StoreController extends AdminController{

    protected $title = '店铺文件管理';

    protected function grid()
    {
        $grid = new Grid(new FileStore());
        $grid->model()->orderBy('id', 'DESC');
        $grid->column('id','ID');
        $grid->column('area.area','站点');
        $grid->column('country.country','国家');
        $grid->column('file_date','文件日期')->display(function ($value){
            return date('Y.m.d',strtotime($value));
        });
        $grid->column('file_type','文件类型')->using(FileStore::$_fileType);
        $grid->column('file_name','文件名');
        $grid->column('user_id','操作人')->display(function ($value){
            return User::getUsernameById($value);
        });
        $grid->column('updated_at','操作时间')->sortable();

        $grid->column('操作')->view('file.store.action');

        if(Admin::user()->can('file.store.edit')){
            $grid->tools(function (Grid\Tools $tools) {
                $tools->append(new ImportFile());
            });
        }

        $grid->disableActions();
        $grid->disableExport();
        $grid->disableCreateButton();
        $grid->disableRowSelector();
        $grid->filter(function($filter){
            $filter->column(1/3, function ($filter) {
                $filter->equal('area_id','站点')->select(AmazonArea::options());
            });
            $filter->column(1/3, function ($filter) {
                $filter->equal('country_id','国家')->select(AmazonCountry::options());
            });
            $filter->column(1/3, function ($filter) {
                $filter->equal('file_type','类型')->select(FileStore::$_fileType);
            });
        });
        return $grid;
    }

    protected function download()
    {
        $id = request('id');
        $f = FileStore::query()->find($id);
        if(!$f) {
            admin_toastr('无文件记录！','error');
            return back();
        }
        try{
            $fileDir = FileStore::fileDir(strtotime($f->file_date));
            $fileName = FileStore::fileName($f->area_id,$f->country_id,$f->file_type,$f->user_id,$f->file_name);
            $file = public_uploads_path($fileDir).DIRECTORY_SEPARATOR.$fileName;
            if(!file_exists($file)){
                admin_toastr('无文件！','error');
                return back();
            }
            return response()->download($file);
        }catch (\Exception $e){
            report($e);
            admin_toastr('操作失败！','error');
            return back();
        }
    }
}
